package com.help10000.rms.mvp.presenter

import android.widget.EditText
import com.alibaba.fastjson.JSON
import com.amir.common.api.CustomObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.LoginEntity
import com.amir.common.beans.TokenEntity
import com.amir.common.mvp.model.Model
import com.amir.common.utils.Constant
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.help10000.rms.R
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.view.LoginView
import kotlinx.android.synthetic.main.fragment_login.btn_login
import okhttp3.MediaType
import okhttp3.RequestBody
import kotlin.random.Random


class LoginPresenter(view: LoginView) : SMSPresenter(view) {

    fun autoLogin(nonceStr:String?, encodePassword:String?, accountName:String?){
        if(encodePassword.isNullOrEmpty()||accountName.isNullOrEmpty()||nonceStr.isNullOrEmpty())return

        val map = mutableMapOf<String, Any>()
        map["accountname"] = accountName
        map["noncestr"] = nonceStr
        map["encodepassword"] = encodePassword
        val body: RequestBody =
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSON(map).toString()
            )
        val login = Model.getServer().AuthorizeByAuto(
            returnurl = "",
            response_type = "code",
            scope = "base",
            state = Random.nextInt(10000).toString(),
            json = body
        )

        Model.getObservable(login, object : CustomObserver<LoginEntity>(view = mvpView) {
            override fun success(t: LoginEntity) {
                t.save()
                getToken(t.code)
            }
        })

    }

    fun loginByValidCode(tel: String, code: String) {
        // 1. 基础校验：提前拦截空值错误
        if (tel.isEmpty()) {
            mvpView.onShow() // 恢复按钮状态
            ToastUtil.show("手机号不能为空")
            return
        }
        if (code.isEmpty()) {
            mvpView.onShow() // 恢复按钮状态
            ToastUtil.show("验证码不能为空")
            return
        }
        val smsId = SPUtils.getString(Constant.SmsId)
        if(smsId.isNullOrEmpty()) {
            return ToastUtil.show("请先发送验证码")
        }

        val map = mutableMapOf<String, Any>()
        map["tel"] = tel
        map["verifycode"] = code
        map["smsid"] = smsId
        val body: RequestBody =
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSON(map).toString()
            )
        val login = Model.getServer().AuthorizeByValidCode(
            returnurl = "",
            response_type = "code",
            scope = "base",
            state = "1234",
            json = body
        )
        // 4. 处理响应：统一错误提示为“验证码错误”，屏蔽技术细节
        Model.getObservable(login, object : CustomObserver<LoginEntity>(view = mvpView) {
            override fun success(t: LoginEntity) {
                // 区分业务状态码：成功/验证码相关错误/其他错误
                when {
                    // 成功场景（0：正常成功，-2：需要自动注册）
                    t.msgCode == 0 || t.msgCode == -2 -> {
                        if (t.msgCode == -2) {
                            // 特殊场景：自动注册后登录
                            val smsId = SPUtils.getString(Constant.SmsId)
                            if (!smsId.isNullOrEmpty()) {
                                regByValidCode(tel, code, smsId)
                            } else {
                                mvpView?.showDialog("验证码会话失效，请重新发送验证码", -1)
                            }
                        } else {
                            // 正常登录成功
                            SPUtils.save(Constant.accoun, tel)
                            t.save()
                            getToken(t.code)
                        }
                    }
                    // 验证码相关业务错误（如验证码错误、过期、不匹配等）
                    else -> {
                        // 统一提示为“验证码错误”，忽略服务器原始 errMsg（避免技术信息）
                        mvpView?.showDialog("验证码错误，请重新输入", t.msgCode)
                        return // 终止后续逻辑
                    }
                }
            }

            // 网络/服务器错误处理：屏蔽 HTTP 500 等技术信息，显示友好提示
            override fun onError(e: Throwable) {
                super.onError(e) // 调用父类默认处理（可选，如关闭加载框）
                // 无论原始错误是什么（500/404/超时等），统一显示网络相关提示
                mvpView?.showDialog("网络异常，请检查网络后重试", -1)
            }
        })
    }
    fun login(etPhone: EditText, etCode: EditText) {

        val account = etPhone.text.toString().trim()
        val psd = etCode.text.toString().trim()

        if (account.isEmpty()) {
            mvpView.onShow()
            return ToastUtil.show("账号不能为空")
        }
        if (psd.isEmpty()) {
            mvpView.onShow()
//            return ToastUtil.show("密码不能为空")
            return ToastUtil.show("密码不能为空")
        }
        val map = mutableMapOf<String, Any>()
        map["acc"] = account
        map["pwd"] = psd
        val body: RequestBody =
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JSON.toJSON(map).toString()
            )
        val login = Model.getServer().login(
            returnurl = "",
            response_type = "code",
            scope = "base",
            state = Random.nextInt(10000).toString(),
            json = body
        )
        Model.getObservable(login, object : CustomObserver<LoginEntity>(view = mvpView) {
            override fun success(t: LoginEntity) {
                SPUtils.save(Constant.accoun, account)
//                SPUtils.save(Constant.pwd, psd)
                t.save()
                getToken(t.code)
            }
        })

    }

    fun bindDeviceId(deviceId: String) {
        val accessToken = SPUtils.getString(Constant.AccessToken)
        val accountId = SPUtils.getString(Constant.accountid)
        if (accountId != null && accessToken != null) {
            val token = Model.getServer().bindDeviceId(accessToken, accountId, deviceId)
            Model.getObservable(token, object : CustomObserver<BaseResult>(mvpView) {

                override fun success(t: BaseResult) {

                }
            })
        }
    }





    override fun getMvpView(): LoginView {
        return super.getMvpView() as LoginView
    }

    fun register(phone: String, smscode: String, nickname: String, pwd: String, affpwd: String) {

        if (phone.isBlank()) {
            mvpView.onShow()
            ToastUtil.show("手机号不能为空")
            return;
        }
        if (smscode.isBlank()) {
            mvpView.onShow()
            ToastUtil.show("验证码不能为空")
            return;
        }
        if (nickname.isBlank()) {
            mvpView.onShow()
            ToastUtil.show("昵称不能为空")
            return;
        }
        if (pwd.isBlank()) {
            mvpView.onShow()
            ToastUtil.show("密码不能为空")
            return;
        }
        if (affpwd.isBlank()) {
            mvpView.onShow()
            ToastUtil.show("确认密码不能为空")
            return;
        }
        if (affpwd != pwd) {
            mvpView.onShow()
            ToastUtil.show("两次密码不一致，请重新输入")
            return;
        }
        val smsId = SPUtils.getString(Constant.SmsId).toString()
        val register = Model.getServer().register(phone, nickname, pwd, smsId, smscode)
        Model.getObservable(register, object : CustomObserver<BaseResult>(mvpView) {
            override fun success(t: BaseResult) {
                mvpView?.registerSucc()
            }
        })
    }
}
